package com.example.common.cfg;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

@Component
public class GuavaCache {

    public LoadingCache<String, String> cache = CacheBuilder.newBuilder()
            //设置缓存初始大小，应该合理设置，后续会扩容
            .initialCapacity(10)
            //最大值
            .maximumSize(100)
            //并发数设置
            .concurrencyLevel(5)
            //缓存过期时间，写入后100秒过期
            .expireAfterWrite(10000, TimeUnit.SECONDS)
            // 此缓存对象经过多少秒没有被访问则过期。
            .expireAfterAccess(10000, TimeUnit.SECONDS)
            //统计缓存命中率
            .recordStats()
            .build(new CacheLoader<String, String>() {
                @Override
                public String load(String key) throws Exception {
                    return "测试1:value:" + key;//当缓存中没有记录时，加载对应的值并返回
                }
            });


    @PostConstruct
    public void init() {
        cache.put("url", "http://localhost:8080/completable/select");
    }

    public String get(String key) throws ExecutionException {
        return cache.get(key);
    }
}

